// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { feedApi } from '/api/feed'
import { checkAuth } from '/store/actions'
import { isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event, $utils } from '/utils'

Component({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    loading: true,
    show: false,
    feedId: 0,
    feed: {} as DomoFeed,
    comments: [] as DomoComment[],
    noMore: false,
    inputValue: '',
    inputFocus: false,
    inputPlaceholder: '',
    replyUser: 0,
    comment_id: 0, // 一级评论ID
    reply_id: 0, // 被回复评论ID
    postType: '', // '':对评论动态；comment:对评论回复即二级评论，reply:对二级评论回复,发布评论/回复
    keyboardOffsetTop: 0,
    access: GlobalData.access,
    index: '',
  },
  pageLifetimes: {
    show() {
      $event.on('showComment', this, ({ feedId, index }: { feedId: number; index: any }) => {
        this.onShow(feedId)
        this.setData({
          isFullScreen: GlobalData.isFullScreen,
          index,
        })
      })
    },
  },
  methods: {
    emptyHandler() {
      console.log('empty')
    },
    async onShow(feedId: number) {
      const { access } = GlobalData
      wx.showLoading({ title: '加载中' })
      this.setData({ show: true, loading: true, feedId, access })
      $event.emit('feed:hideTabbar')
      // const tabBarInstance = this.getTabBar!()
      // if (tabBarInstance) tabBarInstance.setData({ hide: true })
      // // wx.hideTabBar({
      // //   animation: true,
      // // })
      const res = await feedApi.getFeedComments(feedId, { limit: 15 })
      const noMore = res.comments.length < 15
      this.setData({
        comments: res.comments,
        feed: res.feed,
        loading: false,
        noMore,
        inputValue: '',
        inputFocus: false,
        inputPlaceholder: '',
        replyUser: 0,
        comment_id: 0,
        reply_id: 0,
        postType: '',
      })
      wx.hideLoading()
    },
    async onLoadmore() {
      if (this.data.noMore) return
      wx.showLoading({ title: '加载中' })
      const after = $utils.getLastField(this.data.comments)
      const res = await feedApi.getFeedComments(this.data.feedId, { after, limit: 15 })
      const noMore = res.comments.length < 15
      this.setData({
        comments: [...this.data.comments, ...res.comments],
        noMore,
      })
      wx.hideLoading()
    },
    onClose() {
      this.setData({ show: false, pinneds: [], comments: [], feedId: 0 })
      $event.emit('feed:showTabbar')
      // const tabBarInstance = this.getTabBar!()
      // if (tabBarInstance) tabBarInstance.setData({ hide: false })
      // wx.showTabBar({
      //   animation: true,
      // })
    },
    async onCommentFocus() {
      await checkAuth()
    },
    bindkeyboardheightchange(event: WechatMiniprogram.TouchEvent) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      //@ts-ignore
      this.handleKeyboard(this, event)
    },
    handleKeyboard: $utils.throttle((that, event: WechatMiniprogram.TouchEvent) => {
      const { height } = event.detail
      if (height != that.data.keyboardOffsetTop) {
        that.setData({
          commentFocus: true,
          keyboardOffsetTop: height,
        })
      }
    }, 100),
    onInputBlur() {
      this.setData({
        keyboardOffsetTop: 0,
        inputFocus: false,
      })
    },
    onInputComment({ detail = {} }: any, targetValue: string) {
      const value = detail.value
      return {
        value: targetValue || value,
        pos: detail.cursor || 0,
      }
    },
    async onConfirmComment({ detail }: any) {
      if (!isLogin()) {
        await checkAuth()
      }

      const { replyUser, comment_id, reply_id, postType } = this.data

      const payload: PostCommentBody = { body: detail.value }
      /*
      对动态进行一级评论参数：body
      对动态的一级评论进行评论(二级评论)参数：body、reply_user(回复用户)、reply_id(一级评论id)、pid(一级评论id)
      对动态的二级评论进行回复(二级评论的回复)参数：body、reply_user(回复用户)、pid(一级评论id)、reply_id(二级评论id)
      */
      if (replyUser) payload.reply_user = replyUser
      if (comment_id) payload.pid = comment_id
      if (reply_id) payload.reply_id = reply_id
      try {
        const { comment, amount } = await feedApi.postFeedComment(this.data.feedId, payload)
        if (amount) {
          $event.emit('showMessage', {
            message: '评论成功',
            amount: amount,
          } as GetRewardMessageReturns)
        } else {
          wx.showToast({
            title: '评论成功',
            icon: 'success',
            duration: 2000,
          })
        }
        $event.emit('after:comment')
        $event.emit('after:listcomment', this.data.feed.id)
        let comments = this.data.comments as any
        if (postType === 'comment' || postType === 'reply') {
          for (let i = 0; i < comments.length; i++) {
            if (comments[i].id === this.data.comment_id) {
              comments[i].replys = [comment, ...comments[i].replys]
              comments[i].reply_count = comments[i].reply_count + 1
              break
            }
          }
        } else {
          comments = [comment, ...this.data.comments]
        }
        this.setData({
          comments,
          'feed.feed_comment_count': this.data.feed.feed_comment_count + 1,
          inputFocus: false,
          inputValue: '',
          inputPlaceholder: '',
          replyUser: null as any,
          comment_id: 0,
          reply_id: 0,
          postType: '',
        })
      } catch (error) {
        wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
      }
    },
    async onLikeFeed() {
      const { feed } = this.data
      $event.emit('after:onLike', feed.id)
      await checkAuth()
      if (feed.has_liked) {
        feedApi.unlikeFeed(feed.id)
      } else {
        feedApi.likeFeed(feed.id)
      }
      this.setData({
        [`feed.has_liked`]: !feed.has_liked,
        [`feed.like_count`]: feed.like_count + (!feed.has_liked ? 1 : -1),
      })
    },
    async onClick(event: any) {
      if (!isLogin()) {
        await checkAuth()
      }
      const { comment = {}, reply = {}, type = '' } = event.currentTarget.dataset
      this.setData({ postType: type || '' })
      const user_id = type === 'reply' ? reply.user_id : comment.user_id
      if (GlobalData.logged!.id === user_id) {
        wx.showActionSheet({
          itemList: ['删除评论'],
          success: async ({ tapIndex }) => {
            if (tapIndex === 0) {
              try {
                wx.showLoading({ title: '删除中' })
                await feedApi.deleteFeedComment(
                  comment.commentable_id,
                  type === 'reply' ? reply.id : comment.id,
                )

                wx.hideLoading()
                let newList = this.data.comments
                if (this.data.postType === 'reply') {
                  for (let i = 0; i < newList.length; i++) {
                    if (newList[i].id === comment.id) {
                      // @ts-ignore
                      newList[i].replys = newList[i].replys.filter(
                        (item: DomoComment) => item.id !== reply.id,
                      )
                      // @ts-ignore
                      newList[i].reply_count = newList[i].reply_count - 1
                      break
                    }
                  }
                } else {
                  newList = newList.filter((item: DomoComment) => item.id !== comment.id)
                }
                this.setData({
                  comments: newList,
                  'feed.feed_comment_count': this.data.feed.feed_comment_count - 1,
                })
              } catch (error) {
                this.setData({ postType: '' })
                wx.hideLoading()
                wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
              }
            }
          },
        })
      } else {
        this.setData({
          inputFocus: true,
          replyUser: type === 'comment' ? comment.user.id : reply.user.id,
          comment_id: comment.id,
          reply_id: type === 'comment' ? comment.id : reply.id,
          inputPlaceholder: `回复 ${type === 'comment' ? comment.user.name : reply.user.name}:`,
        })
      }
    },
    async onReport(event: any) {
      const { comment = {}, reply = {}, type = '' } = event.currentTarget.dataset
      const user_id = type === 'reply' ? reply.user_id : comment.user_id
      const data = event.currentTarget.dataset
      if (!isLogin()) {
        await checkAuth()
      }
      if (GlobalData.logged!.id === user_id) return
      wx.navigateTo({
        url: `/pages/report/report?type=comment&id=${
          type === 'reply' ? reply.id : data.comment.id
        }`,
      })
    },
    toReply(event: WechatMiniprogram.BaseEvent) {
      const { comment } = event.currentTarget.dataset
      wx.navigateTo({ url: `/pages/feed/reply/reply?id=${comment.id}` })
    },
  },
})
